<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="skin_library">
    <div class="mb-[10px]">
      <el-card shadow="hover">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" size="small" label-width="120px">
          <el-form-item label="铺层代码" prop="plyCode">
            <el-input v-model="queryParams.plyCode" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="是否对称铺层" prop="symmetrical">
            <el-select v-model="queryParams.symmetrical">
              <el-option label="是" value="1"></el-option>
              <el-option label="否" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="padding-left: 120px">
            <el-button type="primary" icon="search" @click="doQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button size="small" type="primary" plain icon="Plus" @click="handleVisible('add', null)">新增铺层</el-button>
            <el-button size="small" type="primary" plain icon="download" @click="handledownload()">导出铺层</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="skinList" :row-key="getRowKeys" @selection-change="handleSelectionChange">
        <el-table-column type="selection" :reserve-selection="true" width="55" align="center" />
        <el-table-column v-for="item in defaultColunms" :key="item.label" :label="item.label" :prop="item.prop" :fixed="item.fixed" align="left">
          <template #default="scope">
            <span v-if="item.type === 'text'">{{ scope.row[item.prop] }}</span>
            <span v-if="item.type === 'map_text'">{{ symmetrical[scope.row[item.prop]] }}</span>
          </template>
        </el-table-column>

        <el-table-column v-for="item in cutColunms" :key="item.label" :label="item.label" :prop="item.prop" />
        <el-table-column label="操作" align="left" width="130" fixed="right">
          <template #default="scope">
            <div>
              <el-tooltip content="修改" placement="top">
                <el-button size="small" link type="primary" icon="EditPen" @click="handleVisible('edit', scope.row)">修改</el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button size="small" link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagenation">
        <pagination
          v-show="total > 0"
          style="margin-top: 0;"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          :total="total"
          :background="false"
          layout="total, sizes, prev, pager, next, jumper"
          @pagination="handleCurrentChange"
        />
      </div>
    </el-card>
    <AddSkinLibrary v-if="addVisible" :add-visible="addVisible" :row-data="currentData" @handle-event="handleEvent" />
  </div>
</template>
<script setup>
import AddSkinLibrary from './AddSkinLibrary.vue';
import { getLayerList, deleteLayer, exportData } from '@/api/layupLibrary';
import { downloadFile } from '@/utils/index';
const addVisible = ref(false);
const eqMaterialVisible = ref(false);
const skinList = ref([]);
const total = ref(0);
const loading = ref(false);
const currentData = ref(null);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  plyCode: '',
  symmetrical: '',
  isAsc: 'descending'
});
const symmetrical = ref({
  '1': '是',
  '0': '否'
});

const defaultColunms = ref([
  { label: '铺层代码', prop: 'plyCode', fixed: 'left', type: 'text' },
  { label: '材料', prop: 'material', fixed: null, type: 'text' },
  { label: '层数', prop: 'layerNumber', fixed: null, type: 'text' },
  { label: '单层厚度', prop: 'thickness', fixed: null, type: 'text' },
  { label: '是否对称铺层', prop: 'symmetrical', fixed: null, type: 'map_text' }
]);

const cutColunms = ref([]);
const selectIds = ref([]);

const getRowKeys = (row) => {
  return row._id;
};
const handleSelectionChange = (val) => {
  selectIds.value = val.map((item) => item._id);
  console.log(selectIds.value);
};
const handledownload = () => {
  const queryParamsData = {
    idList: selectIds.value
  };
  console.log(queryParamsData);
  exportData(queryParamsData)
    .then((res) => {
      if (res?.code === 500) {
        ElMessage({ showClose: true, message: '下载失败。', type: 'error' });
        return;
      }
      downloadFile(res, '铺层库', 'xlsx');
    })
    .catch(() => {
      loading.value = false;
    });
};

const handleEvent = (data) => {
  if (data?.type === 'eqMaterial') {
    eqMaterialVisible.value = false;
  } else if (data?.type === 'refresh') {
    addVisible.value = false;
    doQuery();
  } else {
    addVisible.value = false;
  }
};
const handleVisible = (type, data) => {
  currentData.value = data;
  if (type === 'add') {
    currentData.value = null;
    addVisible.value = true;
  }
  if (type === 'edit') {
    addVisible.value = true;
  }
  if (type === 'eqMaterial') {
    eqMaterialVisible.value = true;
  }
};
// 删除
const handleDelete = (data) => {
  ElMessageBox.confirm('是否确认删除该项？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteLayer(data._id).then((res) => {
      ElMessage({ showClose: true, message: '删除成功。', type: 'success' });
      doQuery();
    });
  });
};
const doQuery = () => {
  skinList.value = [];
  loading.value = true;
  getLayerList(queryParams.value)
    .then((res) => {
      if (res) {
        // 处理铺层
        const data = res?.rows || [];
        const lengthArr = [];
        if (data) {
          // 清空数据
          cutColunms.value = [];
          data.forEach((element) => {
            const layerArr = element.data.split(',') || [];
            lengthArr.push(layerArr.length);
            layerArr.map((el, index) => {
              const label = `PLY${index + 1}`;
              element[label] = el;
            });
          });
        }
        const maxLength = Math.max(...lengthArr);
        for (let i = 0; i < maxLength; i++) {
          cutColunms.value.push({ label: `PLY${i + 1}`, prop: `PLY${i + 1}` });
        }
        skinList.value = data;
        total.value = res?.total || 0;
      }
    })
    .finally(() => {
      loading.value = false;
    });
};
const handleCurrentChange = () => {
  doQuery();
};
onMounted(() => {
  doQuery();
});
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    plyCode: '',
    symmetrical: '',
    isAsc: 'descending'
  };
  doQuery();
};
</script>
<style lang="scss" scoped>
.skin_library {
  padding: 0.5rem;
  height: calc(100vh - 84px);
  overflow: auto;
  width: 100%;
  .pagenation {
    display: flex;
    justify-content: end;
    margin-top: 10px;
  }
}
</style>
